import { userInfo, userProFile } from '@/api/user'
import { getToken, setToken } from '@/utils/auth'
import { resetRouter } from '@/router/index'

export default {
  namespaced: true,
  state: () => {
    return {
      // 保存token
      token: getToken() || '',
      // 用户信息
      userInfo: {}
    }
  },
  mutations: {
    setUserInfo(state, newUserInfo) {
      state.userInfo = newUserInfo
    },
    // 定义mutation去修改token
    // mutation的名字(state,newToken){}
    setToken(state, newToken) {
      // 1.保存token到state
      state.token = newToken
      // 2.调用封装好的函数,做持久化
      setToken(newToken)
    }
  },
  actions: {
    async getUserProFile(context) {
      const res = await userProFile()
      const obj = await userInfo(res.data.userId)
      const obj1 = { ...res.data, ...obj.data }
      //   console.log(obj1)
      context.commit('setUserInfo', obj1)
      return res
    },
    // 用户退出
    logout(context) {
      context.commit('setUserInfo', {})
      context.commit('setToken', '')

      // 退出重置路由
      resetRouter()
    }
  },
  getters: {}
}
